import { ProjectName } from '@/common/constants'

export function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
  return key in object
}

// 获取 url 查询参数
export function getQueryString() {
  const result: any = {}
  const questString = window.location.search.substring(1) || window.location.hash.split('?')[1]
  const re = /([^&=]+)=([^&]*)/g
  let m: any = ''

  // eslint-disable-next-line no-cond-assign
  while ((m = re.exec(questString))) {
    result[decodeURIComponent(m[1]) as string] = decodeURIComponent(m[2])
  }

  return result
}

export function flatRouters(routes: any) {
  const menus: any = []

  function getRouters(menu: any) {
    menu.forEach((item: any) => {
      if (!item.children) {
        menus.push(item)
      } else {
        getRouters(item.children)
      }
    })
  }

  getRouters(routes)

  return menus
}

export function setPageTitle(titleText: string) {
  document.title = `${titleText || ''} - ${ProjectName}`
}
